<!--
 * @description: 文件描述
 * @version: 0.0.1
 * @author: xxx
 * @Date: 2024-10-29 11:02:46
-->
<template>
	<scroll-view :scroll-top="scrollTop" scroll-y="true" style="height: 100vh;width: 100%;">
		<view class="goodsLettering">
			<loading :showLoaded.sync="showLoaded"></loading>
			<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
			<view class="goodsLettering-box">
				<view class="goodsLettering-container">
					<view class="goodsLettering-img-box">
						<c2b-canvas ref="c2bCanvas" :previewImg="previewImg" @canvasFun="canvasFun" />
					</view>
					<view class="container-content">
						<!-- 输入框 -->
						<view class="container-text-area">
							<view class="input-box" @click="changeFocus">
								<textarea style="position: absolute; left: -9999px" type="text" confirm-type="return"
									@confirm="confirmSub" :show-confirm-bar="true" :focus="isFocus" @blur="onBlur"
									v-model="textareaValue" @keyboardheightchange="handleKeyboardHeightChange"
									:adjust-position="true" @input="handleInput" class="input" placeholder="请输入内容..." />
								<view>
									<!-- 一行 -->
									<view class="item_length">
										<view class="emoji-box" v-if="preview.length || cursorState == 2">
											<view class="emoji-item" v-for="(item, index) in preview" :data-emoji="item"
												:key="index">
												<view class="emoji-icon-box" v-if="['＆', '♡', '☆', '□'].includes(item)">
													<view :class="[
														'emoji',
														`emoji-${['＆', '♡', '☆', '□'].indexOf(item) + 1
														}-black`,
													]">
													</view>
												</view>
												<view class="emoji-preview" :class="{ placeholder: item == ' ' }"
													v-else>
													{{ item }}
												</view>
											</view>
											<view class="cursor" v-if="cursorState === 1 && isFocus">
											</view>
										</view>

										<view class="emoji-box def-content" v-if="
											!preview.length && !preview1.length && cursorState == 1
										">
											<view class="cursor" v-if="cursorState === 1 && isFocus">
											</view>
											<view v-else style="width: 2rpx; height: 1em"> </view>
											{{ placeholderText }}
										</view>
										<!-- <view class="text-num">
											{{ textLength || 0 }}/50
										</view> -->
									</view>

									<!-- 二行 -->
									<view class="emoji-box" v-show="preview1.length">
										<view class="emoji-item" v-for="(item, index) in preview1" :data-emoji="item"
											:key="index">
											<view class="emoji-icon-box" v-if="['＆', '♡', '☆', '□'].includes(item)">
												<view :class="[
													'emoji',
													`emoji-${['＆', '♡', '☆', '□'].indexOf(item) + 1
													}-black`,
												]">
												</view>
											</view>
											<view class="emoji-preview" :class="{ placeholder: item == ' ' }" v-else>
												{{ item }}
											</view>
										</view>
										<view class="cursor" v-if="cursorState === 2 && isFocus">
										</view>
									</view>
								</view>
							</view>
						</view>
						<!-- 字符选择 
						  ＆->＆ ＆
						  ♡->心 ♡
						  ☆-> ★ ☆
						   □->礼物  □
						  -->
						<view class="container-symbol">特殊符号选择：
							<view class="radio-icon-box" @touchstart="handleTouchStart('img2State')"
								@touchend="handleTouchEnd()" style="margin-right: 24rpx">
								<view @click.stop="(e) => seticon(e)" data-value="＆" class="selectIconStyle"
									:style="selectIconUrl2">
								</view>
							</view>
							<view class="radio-icon-box" @touchstart="handleTouchStart('img1State')"
								@touchend="handleTouchEnd()" style="margin-right: 24rpx">
								<view @click.stop="(e) => seticon(e)" data-value="♡" class="selectIconStyle"
									:style="selectIconUrl1">
								</view>
							</view>

							<view class="radio-icon-box" @touchstart="handleTouchStart('img3State')"
								@touchend="handleTouchEnd()" style="margin-right: 24rpx">
								<view @click.stop="(e) => seticon(e)" data-value="☆" class="selectIconStyle"
									:style="selectIconUrl3">
								</view>
							</view>
							<view class="radio-icon-box" @touchstart="handleTouchStart('img4State')"
								@touchend="handleTouchEnd()">
								<view @click.stop="(e) => seticon(e)" data-value="□" class="selectIconStyle"
									:style="selectIconUrl4">
								</view>
							</view>
						</view>
						<view v-if="optionList.length" class="container-symbol option_img_box">
							<view class="option_title">
								{{ optionTitle }}
							</view>

							<view class="option_item">
								<view v-if="optionName1" class="radio-icon-box" style="margin-right: 24rpx;"
									@click.stop="(e) => changeNewYearImg('img1')">
									<view class="selectIconStyle_newYear" :style="selectIconUrl5">
									</view>
									<view>
										{{ optionName1 }}
									</view>
								</view>
								<view v-if="optionName2" class="radio-icon-box" style="margin-right: 24rpx;"
									@click.stop="(e) => changeNewYearImg('img2')">
									<view class="selectIconStyle_newYear" :style="selectIconUrl6">
									</view>
									<view>
										{{ optionName2 }}
									</view>
								</view>
							</view>

						</view>
					</view>
				</view>

				<view class="btn-continner" :style="{ marginTop: rulesMarginTop + 'rpx' }">
					<view class="attention">
						<!-- <image style="width: 100%; height: auto" :src="rulesTexts" mode="widthFix"></image> -->
						<view v-for="(item, index) in rulesTexts" :key="index">
							<text v-if="item.label1 === 'rules_text'" style="color: #757575">{{ item.text
							}}<text class="bold_text" @click.stop="changeRules" style="
								color: #1a1a1a;
								font-weight: 500;
								font-size: 20rpx;
								font-family: FrankNew-Regular, NotoSansSC-Medium;
								">《{{ rulesTitle }}》</text></text>
							<text class="def_text" style="
								color: #757575;
								font-size: 20rpx;
								font-family: FrankNew-Regular, NotoSansSC-Regular;
							" v-else>
								{{ item.text }}
							</text>
						</view>

						<view class="hot_region" @click="changeRules"></view>
					</view>
					<view class="check-rules" @click.stop="handleChangeCheckStatus">
						<view class="check-icon">
							<image v-if="!userCheckStatus"
								src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/uncheck.png">
							</image>
							<image v-else
								src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/check.png">
							</image>
						</view>
						<view class="check-text">
							我已知悉并同意<text @click.stop="changeRules" class="bold_text">《{{ rulesTitle }}》</text>
						</view>
					</view>

					<view class="btn-box">
						<button class="btn" :class="[submitState() ? 'submit-btn' : 'disabel-btn-style']"
							@click="onSubmit">
							提交
						</button>
					</view>
				</view>
				<!-- 清除时 弹窗 -->
				<c2bToast ref="c2bToastPopup" @onEnterC2bToast="onEnterC2bToast" />
				<!-- 个性化定制内容查看 -->
				<c2bdetails ref="c2bDetailsPopup" @onC2bDetailsEvent="onC2bDetailsEvent"></c2bdetails>
				<!-- 弱提示 弹窗 -->
				<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
			</view>
		</view>
	</scroll-view>
</template>
<script>
import NavBar from "@/components/common/navbar";
import loading from "@/components/common/loading";
import c2bCanvas from "./components/c2bCanvasNew.vue";
import c2bdetails from "./components/c2bDetails.vue";
import c2bToast from "./components/c2bToast.vue"
import api from "@/api/api";
import { CUSTOMER_INFO, USER_INFO, MERCHANT_INFO } from "@/utils/constant";
import valiDatorZhText from "./zhText.json";

import ZHText from "./components/CN-unicode.json";
import ENText from "./components/EN-unicode.json";
import ICONfONT from "./components/ICON-unicode.json";
export default {
	components: {
		navBar: NavBar,
		loading: loading,
		c2bdetails,
		c2bCanvas,
		c2bToast
	},
	data() {
		return {
			showLoaded: true,
			isShowCustomNavBar: true,
			// 组件所需的参数
			navbarData: {
				showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
				title: "商品详情", //导航栏 中间的标题
				hideHome: true,
			},
			textareaValue: "",
			preview: [], //1行
			preview1: [], //2行
			isFocus: false,
			img1State: false,
			img2State: false,
			img3State: false,
			img4State: false,
			imgState1: false,
			imgState2: false,
			productSKU: "",
			itemId: "",
			valueId: "",
			canvas: null,
			canvasStyle: null,
			previewImg: "",
			userCheckStatus: false,
			rulesTexts: [],
			rulesTitle: "",
			cursorState: 1, //光标默认显示在第一行
			debounceGetSwiperImg: null,
			changeState: false,
			historyNewVal: "",
			historyOldVal: "",
			fontSizePt: 92, //计算时字体的大小
			fontCHwidth: 1000, //
			lineWidthVal: 780, //默认一行width
			textWidth1: 0, // 第二行width
			keyWordSatae: false,
			offCanvasWidth: 780,
			// 新年字符 图片
			img1List: [],
			img2List: [],
			newYearState: '',
			canvasPreviewImg: [],
			placeholderText: '请输入您的镌刻内容',
			enterNewYear: true,
			loadingState: false,
			rulesMarginTop: 20,
			optionList: [],
			optionTitle: '',
			optionName1: '',
			optionName2: '',
			valitatorDrawCanvas: true,
		};
	},
	computed: {
		selectIconUrl1() {
			const url = this.img1State
				? "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon-1-true.png"
				: "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon-1-false.png";
			return `background-image:url(${url})`;
		},
		selectIconUrl2() {
			const url = this.img2State
				? "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon_-2-true.png"
				: "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon_-2-false.png";
			return `background-image:url(${url})`;
		},
		selectIconUrl3() {
			const url = this.img3State
				? "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon-3-true.png"
				: "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon-3-false.png";
			return `background-image:url(${url})`;
		},
		selectIconUrl4() {
			const url = this.img4State
				? "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon-4-true.png"
				: "https://100000063-1252208446.file.myqcloud.com/images/刻字/selectIcon-4-false.png";
			return `background-image:url(${url})`;
		},
		selectIconUrl5() {
			const url = this.imgState1 ?
				'https://100000063-1252208446.file.myqcloud.com/images/刻字/Plus@3x.png' :
				'https://100000063-1252208446.file.myqcloud.com/images/刻字/Plus@2x.png'
			return `background-image:url(${url})`
		},
		selectIconUrl6() {
			const url = this.imgState2 ?
				'https://100000063-1252208446.file.myqcloud.com/images/刻字/Plus@3x.png' :
				'https://100000063-1252208446.file.myqcloud.com/images/刻字/Plus@2x.png'
			return `background-image:url(${url})`
		}
	},
	watch: {
		textareaValue(newValue, oldValue) {
			this.historyNewVal = newValue;
			this.historyOldVal = oldValue;

			// 监听用户换行
			if (newValue.indexOf("\n") != -1) {
				const arr = [];
				const preview = this.preview;
				for (let i = 0; i < preview.length; i++) {
					if (preview[i].indexOf("\n") === -1) {
						arr.push(preview[i]);
					}
				}
				this.cursorState = 2;
				// 计算换行长度
				let textWidth = 0;
				for (let j = 0; j < arr.length; j++) {
					textWidth += this.getOffTextLength(arr[j]);
				}
				this.lineWidthVal = textWidth;
				this.textWidth1 = textWidth;
			} else {
				if (this.preview1.length) return
				// 重置限制换行字符宽度
				this.lineWidthVal = this.offCanvasWidth;
			}
		},
	},
	async onLoad(option = {}) {
		try {
			await this.getFont();
			if (!option.itemId || !option.valueId) return console.log("参数错误");
			this.itemId = option.itemId;
			this.valueId = option.valueId;
			const imgArr = await this.getGoodsDetail(option.itemId);
			const imgs = imgArr.map(i => i.url.split('?')[0])
			this.previewImg = imgs
			this.canvasPreviewImg = imgs
			await this.$refs.c2bCanvas.initCanvas(true);
			this.getRulesUtoolsData();
			await this.getUtoolsJsonByRelevance()
			if (option.type && option.type === "toGoodsLetteringNew") {
				// 从订单页进来
				const _info = uni.getStorageSync("userCustomizationDetails");
				this.preview = _info.submitArr[0].length ? _info.submitArr[0] : [];
				this.preview1 = _info.submitArr[1].length ? _info.submitArr[1] : [];

				if (_info.newYearState) {
					this.preview = []
					this.preview1 = []
					this.placeholderText = (_info.newYearState && _info.newYearState == "img1") ? this.optionName1 : this.optionName2
					this.newYearState = _info.newYearState
					this.previewImg = _info.subImg
					if (this.newYearState == 'img1') {
						this.imgState1 = true
					} else {
						this.imgState2 = true
					}
				} else {
					this.textareaValue = this.preview.concat(this.preview1).join("");
					if (this.preview1.length) {
						const arr = this.preview
						this.cursorState = 2;
						// 计算换行长度
						let textWidth = 0;
						for (let j = 0; j < arr.length; j++) {
							textWidth += this.getOffTextLength(arr[j]);
						}
						this.lineWidthVal = textWidth;
						this.textWidth1 = textWidth;
					}
					let obj = {
						detail: {
							value: this.textareaValue,
						},
					};
					this.handleInput(obj);
					this.cursorState = this.preview1.length ? 2 : 1;
					this.previewImg = await this.$refs.c2bCanvas.getSwiperImg(
						this.preview,
						this.preview1
					);
				}
				this.userCheckStatus = true;

			}
		} catch (error) {
			console.log(error, "onLoad");
		}

		this.showLoaded = false;
	},
	async mounted() {
		// 初始化防抖函数
		this.debounceGetSwiperImg = this.debounce(
			this.$refs.c2bCanvas.getSwiperImg,
			500
		);
		this.debounceValidatorText = this.debounce(
			this.validatorText,
			500
		);
	},
	onHide() { },
	async onShow() { },
	methods: {
		async handleKeyboardHeightChange(event) {
			this.changeState = true
			try {
				const h = event.detail.height
				this.isFocus = !!h
				if (!h && this.keyWordSatae) {
					if (!this.historyNewVal.length && !this.historyOldVal.length) return
					if (this.textareaValue) {
						// 文字校验
						const isValidator = await this.debounceValidatorText(this.textareaValue);
						if (!isValidator) {
							uni.showLoading({
								title: "预览生成中",
								mask: true
							});
							this.loadingState = true
							this.previewImg = await this.$refs.c2bCanvas.getSwiperImg(this.preview, this.preview1)
						} else {
							// this.validatorSlice()
							this.changeState = false
						}
					} else {
						if (this.newYearState) return
						uni.showLoading({
							title: "预览生成中",
							mask: true
						});
						this.loadingState = true
						this.previewImg = await this.$refs.c2bCanvas.getSwiperImg(this.preview, this.preview1)
						this.changeState = false
					}

					uni.hideLoading();
					this.loadingState = false
				}
				this.keyWordSatae = true
			} catch (error) {
				console.log(error, "handleKeyboardHeightChange");

			}
		},
		validatorSlice() {
			// 1、有第二行截取第二行最后一位 反之截取第一行最后一位
			let preview = this.preview;
			let preview1 = this.preview1;
			let previewLength = preview.length;
			let preview1Length = preview1.length;
			if (previewLength && preview1Length) {
				preview1 = preview1.slice(0, preview1Length - 1);
			} else {
				preview = preview.slice(0, previewLength - 1);
			}
			this.preview = preview
			this.preview1 = preview1
			this.textareaValue = preview.concat(preview1).join("");
			this.cursorState = preview1.length ? 2 : 1;
		},
		canvasFun() {
			this.changeState = false
		},
		changeRules() {
			uni.navigateTo({
				url: "/pages/utcms/utcms?uttype=c2bRules",
			});
		},
		async confirmSub() {
		},
		submitState() {
			return (
				((this.preview.length || this.preview1.length) || this.newYearState) && this.userCheckStatus
			);
		},
		//  获取utools数据
		async getRulesUtoolsData(option) {
			try {
				this.rulesTexts = [];
				const that = this;
				let json = await api.getUtoolsJson({
					type: "c2bRulesEnter",
				});
				this.rulesTitle = "麦卡伦定制刻字服务细则";
				if (json && json.success && json.data) {
					const _utoolsData = JSON.parse(json.data);
					if (_utoolsData.children && _utoolsData.children.length) {
						_utoolsData.children.forEach((item) => {
							if (
								item.type === "text" &&
								item.text &&
								item.label1 === "title"
							) {
								that.rulesTitle = item.text;
							} else if (
								item.type === "text" &&
								item.text &&
								item.label1 !== "title"
							) {
								that.rulesTexts.push(item);
								if (item.label1 && item.label1 !== 'rules_text' && Number(item.label1) != NaN) {
									this.rulesMarginTop = Number(item.label1)
								}
							}
						});
					}
				}
			} catch (error) {
				console.log(error, "getRulesUtoolsData");
			}
		},
		async getUtoolsJsonByRelevance() {
			try {
				const json = await api.getUtoolsJsonByRelevance({
					relevance: this.itemId,
					type: 'item_c2b'
				})
				if (json.success && json.data) {
					const resList = JSON.parse(json.data)
					if (!resList.lists || !resList.lists.length) return
					this.optionList = resList.lists
					this.optionTitle = resList.title
					if (!!resList.lists[0]) {
						this.optionName1 = resList.lists[0].imgName
						this.img1List = [resList.lists[0].bigImg, resList.lists[0].detailImg]
					}
					if (!!resList.lists[1]) {
						this.optionName2 = resList.lists[1].imgName
						this.img2List = [resList.lists[1].bigImg, resList.lists[1].detailImg]
					}
				}
			} catch (error) {
				console.log(error, 'getUtoolsJsonByRelevance')
			}
		},
		handleChangeCheckStatus() {
			this.userCheckStatus = !this.userCheckStatus;
		},
		handleTouchStart(val) {
			if (this.loadingState) return
			this.handleTouchEnd();
			switch (val) {
				case "img1State":
					this.img1State = true;
					break;
				case "img2State":
					this.img2State = true;
					break;
				case "img3State":
					this.img3State = true;
					break;
				case "img4State":
					this.img4State = true;
					break;
				default:
					break;
			}
		},
		handleTouchEnd() {
			this.img1State = false;
			this.img2State = false;
			this.img3State = false;
			this.img4State = false;
		},

		async getFont() {
			const res = await this.setfont(
				"Dancing-One",
				"https://100000063-1252208446.file.myqcloud.com/fonts/revamp/Dancing-Script.otf"
			);
			if (!res)
				await this.setfont(
					"Dancing-One",
					"https://100000063-1252208446.file.myqcloud.com/fonts/revamp/Dancing-Script.otf"
				);
			const res1 = await this.setfont(
				"Dancing-Xt",
				'https://100000063-1252208446.file.myqcloud.com/fonts/revamp/xk.ttf'
			);
			if (!res1)
				await this.setfont(
					"Dancing-Xt",
					'https://100000063-1252208446.file.myqcloud.com/fonts/revamp/xk.ttf'
				);
			const res2 = await this.setfont(
				"Dancing-icon",
				"https://100000063-1252208446.file.myqcloud.com/fonts/revamp/Macallan-icon2-1.ttf"
			);
			if (!res2) await this.setfont(
				"Dancing-icon",
				"https://100000063-1252208446.file.myqcloud.com/fonts/revamp/Macallan-icon2-1.ttf"
			);

		},
		async setfont(family, source) {
			return new Promise((resolve, reject) => {
				wx.loadFontFace({
					family: family,
					source: `url("${source}")`,
					scopes: ["webview", "native"],
					success: (e) => {
						resolve(true);
					},
					fail: (e) => {
						reject(false);
					},
					complete: (e) => { },
				});
			});
		},

		async onC2bDetailsEvent() {
			const userData = {}
			try {
				uni.showLoading({
					title: "正在加载",
					mask: true
				});
				this.loadingState = true

				const preview = this.preview.filter(item => item !== "\n");
				const preview1 = this.preview1.filter(item => item !== "\n");
				userData.submitArr = [preview, preview1]
				if (this.newYearState) {
					const text = this.newYearState == "img1" ? this.optionName1 : this.optionName2
					userData.submitArr = [[text], []]
					userData.subImg = [this.previewImg[0], this.previewImg[1]]
					userData.newYearState = this.newYearState
				} else {
					const url = await this.uploadFile(this.previewImg[0])
					const url1 = await this.uploadFile(this.previewImg[1])
					userData.subImg = [url, url1]
				}
				uni.setStorageSync('userCustomizationDetails', userData);
				await this.buyNowRequest();

			} catch (error) {
			}
			uni.hideLoading();
			this.loadingState = false
		},
		// 提交
		async onSubmit() {
			if (!this.userCheckStatus) return this.handleShowTextToast("请勾选麦卡伦定制刻字服务细则");
			this.agreeProtocol(this.userCheckStatus, this.textareaValue)
			const testLength = this.preview.concat(this.preview1);
			if (this.changeState || this.loadingState) return;
			if (!this.newYearState) {
				const regex = /[\n\r]+/;
				let filteredArray = testLength.every((item) => item == " " || regex.test(item));
				// 全是空格
				if (filteredArray) {
					return this.handleShowTextToast("请输入正确内容");
				}
				uni.showLoading({
					title: "正在加载",
					mask: true
				});
				this.loadingState = true
				const isValidator = await this.validatorText(this.textareaValue);
				if (!isValidator) {
					if (!this.valitatorDrawCanvas) {
						this.previewImg = await this.$refs.c2bCanvas.getSwiperImg(this.preview, this.preview1)
					}
					this.valitatorDrawCanvas = true
					const submitArr = [this.preview, this.preview1];
					this.$refs.c2bDetailsPopup.show(this.previewImg, submitArr);
					uni.setStorageSync("submitArr", submitArr);
				} else {
					// this.validatorSlice()
					// this.handleShowTextToast("含敏感文字，请修改");
					this.valitatorDrawCanvas = false

				}
				uni.hideLoading();
				this.loadingState = false
			} else {
				const text = this.newYearState == "img1" ? this.optionName1 : this.optionName2
				const submitArr = [[text], []]
				this.$refs.c2bDetailsPopup.show(this.previewImg, submitArr)
				uni.setStorageSync('submitArr', submitArr)
			}
		},

		// 同意定制协议
		async agreeProtocol(userCheckStatus, customization) {
			try {
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo
				const res = await api.agreeAgreement({
					method: 'POST',
					header: {
						jwt: customerInfo.jwt
					},
					query: {
						customization,
						agree: Number(userCheckStatus),
					}
				})
			} catch (error) {
				console.log(error, 'agreeProtocol')
			}
		},
		async onEnterC2bToast(val) {
			if (this.changeState || this.loadingState) return;
			if (val) {
				if (this.newYearState == 'img1') {
					if (this.imgState1) return
					this.imgState1 = true
					this.imgState2 = false
					this.placeholderText = this.optionName1
				} else {
					if (this.imgState2) return
					this.imgState2 = true
					this.imgState1 = false
					this.placeholderText = this.optionName2

				}
				this.preview = []
				this.preview1 = []
				this.textareaValue = ''

				this.cursorState = 1
				this.previewImg = this.newYearState == 'img1' ? this.img1List : this.img2List
			} else {
				this.newYearState = ''
			}
		},
		async changeNewYearImg(e) {
			if (this.loadingState || this.changeState) return;
			this.newYearState = e
			const previewList = this.preview.concat(this.preview1)
			if (previewList.length) {
				this.$refs.c2bToastPopup.Show()
			} else {
				this.onEnterC2bToast(true)
			}



		},

		uploadFile(path) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: api.uploadFiles,
					filePath: path,
					name: "file", // 固定 // 请求头一定要加，否则 iOS 图片上传会失败
					header: {
						"content-type": "multipart/form-data",
					},
					success(res) {
						const aa = JSON.parse(res.data).data;
						resolve(aa.url);
					},
					fail: function (err) { },
					complete(res) { },
				});
			});
		},
		seticon(e) {
			const { value } = e.currentTarget.dataset;
			let obj = {
				detail: {
					value: this.textareaValue + value,
				},
			};
			this.handleInput(obj, true);
		},
		getOffTextLength(text) {
			const textEN = /[a-zA-Z/]+/;
			const textNumber = /[0-9/]+/;
			const textZH = /[\u4e00-\u9fa5]/;
			const textSpace = /\s/;
			const symbolPattern = /[ℵ∇∂∞]/;
			const ENregex = /[a-zA-Zℵ∇∂∞/]+/;
			const zhTextSymbol = /[“”，。、！；‘’：]/;
			const enTextSymbol = /[""'', .!;’:%]/;
			const numberRegex = /[0-9/]+/;
			const symbolText = ["＆", "□", "☆", "♡"];
			const regex = /[\n\r]+/;
			if (regex.test(text)) return 0;

			try {
				let xWidth = 0;
				let textWidth = 0;
				if (symbolText.includes(text)) {
					ICONfONT.forEach((el) => {
						if (el.t === text) {
							// 将字体单位的宽度转换为像素
							textWidth = (this.fontSizePt / this.fontCHwidth) * el.w;
						}
					});
				} else if (
					textNumber.test(text) ||
					textZH.test(text) ||
					zhTextSymbol.test(text)
				) {
					ZHText.forEach((el) => {
						if (el.t === text) {
							// 将字体单位的宽度转换为像素
							textWidth = (this.fontSizePt / this.fontCHwidth) * el.w;
						}
					});
				} else if (textEN.test(text) || enTextSymbol.test(text)) {
					ENText.forEach((el) => {
						if (el.t === text) {
							// 将字体单位的宽度转换为像素
							textWidth = (this.fontSizePt / this.fontCHwidth) * el.w;
						}
					});
				}
				return textWidth;
			} catch (error) {
				console.log(error, "getOffTextLength");
			}
		},
		async handleInput(e, iconDraw = false) {
			if (this.loadingState) return
			try {
				if (this.newYearState) {
					this.previewImg = this.canvasPreviewImg
					this.placeholderText = '请输入您的镌刻内容'
					this.imgState1 = false
					this.imgState2 = false
					this.newYearState = ''
				}

				let detailVal = e.detail.value;
				let textVal = this.textareaValue;
				// 定义允许输入的符号   ＆♡☆□
				const disallowedChars =
					/[^a-zA-Z0-9\u4e00-\u9fa5\s“”""''’‘，,.、！!;；。’%：:＆♡☆□]/g;
				// const disallowedChars = /[^a-zA-Z0-9\u751f\u65e5\u5feb\u4e50\s“”""’‘''，,.、！!;；。’＆♡☆□]/g;
				if (disallowedChars.test(detailVal)) {
					// 过滤掉不允许的符号
					textVal = textVal.replace(disallowedChars, "");
					detailVal = detailVal.replace(disallowedChars, "");
					this.handleShowTextToast("不支持输入当前符号");
				}
				const textZH = /[\u4e00-\u9fa5]/;
				let isShowToast = false;
				let newTextVal = "";
				let newDetailVal = "";
				const textArr = detailVal.split("");

				for (let i = 0; i < textArr.length; i++) {
					const item = textArr[i];
					if (textZH.test(item)) {
						if (valiDatorZhText.includes(item)) {
							newTextVal += item;
							newDetailVal += item;
						} else {
							isShowToast = true;
						}
					} else {
						newTextVal += item;
						newDetailVal += item;
					}
				}
				textVal = newTextVal;
				detailVal = newDetailVal;
				if (isShowToast) {
					this.handleShowTextToast("该字符不在刻字范围内");
				}
				const arr = detailVal.split("");
				let preview = arr.filter(
					(item, index) => item !== "\n" || index === arr.indexOf("\n")
				);
				let textWidth = 0;
				this.textWidth1 = 0;
				const line1 = [];
				const line2 = [];
				for (let i = 0; i < preview.length; i++) {
					const item = preview[i];
					textWidth += this.getOffTextLength(item);
					if (textWidth <= this.lineWidthVal) {
						line1.push(item);
						this.textWidth1 = this.lineWidthVal;
					} else {
						this.textWidth1 += this.getOffTextLength(item);
						if (
							this.textWidth1 > this.lineWidthVal &&
							this.textWidth1 <= this.lineWidthVal + this.offCanvasWidth
						) {
							line2.push(item);
						} else {
							this.handleShowTextToast("输入内容超出画布，已为您自动截取");
						}
					}
				}
				this.preview = line1;
				this.preview1 = line2;
				// 光标状态
				if (line2.length) {
					this.cursorState = 2;
				} else {
					this.cursorState = 1;
				}
				// 视图不更新问题
				this.$nextTick(async () => {
					this.textareaValue = line1.concat(line2).join("");
					// if (iconDraw) {
					// this.changeState = true
					const isValidator = await this.validatorText(this.textareaValue);
					if (!isValidator) {
						if (iconDraw) {
							this.changeState = true
							await this.loadPreviewImage();
						}
					} else {
						this.validatorSlice()
						this.handleShowTextToast("含敏感文字，请修改");
					}
					// }
				});
			} catch (error) {
				console.error("handleInput", error);
			}
		},

		async loadPreviewImage() {
			this.changeState = true
			uni.showLoading({
				title: "预览生成中",
				mask: true
			});
			this.loadingState = true
			try {
				this.previewImg = await this.debounceGetSwiperImg(
					this.preview,
					this.preview1
				);
			} catch (error) {
				console.error("加载预览图失败", error);
			} finally {
				uni.hideLoading();
				this.loadingState = false
			}
		},

		// 防抖函数
		debounce(func, wait) {
			let timeout;
			return async function (...args) {
				const context = this;
				clearTimeout(timeout);
				return new Promise((resolve) => {
					timeout = setTimeout(async () => {
						resolve(await func.apply(context, args));
					}, wait);
				});
			};
		},

		async validatorText(content) {
			let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
			const accountInfo = uni.getAccountInfoSync();
			let appId = accountInfo.miniProgram.appId;
			const res = await api.checkTextV2(
				{
					method: "POST",
					header: {
						"Content-Type": "application/json",
					},
					query: {
						content: content,
						openid: customerInfo.openId,
						scene: 2,
						version: 2,
					},
				},
				appId
			);
			if (res.data.result.suggest !== "pass") {
				this.handleShowTextToast("含敏感文字，请修改");
				this.valitatorDrawCanvas = false
				return true;
			} else {
				return false;
			}
		},

		changeFocus() {
			this.isFocus = true;
			this.cursorState = this.preview1.length ? 2 : 1;
		},

		onBlur() {
			this.isFocus = false;
		},
		async getGoodsDetail(goodsId) {
			let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
			let merchantInfo = uni.getStorageSync("merchantInfo");
			const json = await api.goodsDetail(
				{
					query: {
						merchant_id: merchantInfo.cloudMerchantId,
						store_id: merchantInfo.cloudMerchantStoreId,
					},
				},
				goodsId
			);
			if (json.code === 1000) {
				const skus = json.data.skus;
				for (var i = 0; i < skus.length; i++) {
					if (skus[i].skuProperties[0].valueId == parseInt(this.valueId)) {
						this.productSKU = skus[i].skuId;
					}
				}
				return json.data.resources.filter(
					(i) => i.kind == "size" && this.valueId == i.valueId
				);
			}
		},

		//	立即购买 数据提交
		async buyNowRequest() {
			try {
				let that = this;
				let userInfo = uni.getStorageSync(USER_INFO);
				let customerInfo =
					uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
				let productSKU = JSON.stringify(this.productSKU);
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
				let skuIdArr = [];
				skuIdArr[0] = productSKU;
				let res = await api.buyNow({
					method: "POST",
					header: {
						jwt: customerInfo.jwt,
					},
					query: {
						customerId: customerInfo.customerId,
						merchantId: merchantInfo.cloudMerchantId,
						orderSource: "wxapp",
						skuId: productSKU,
						qty: 1,
						storeId: merchantInfo.cloudMerchantStoreId,
						captchaTicket: "",
					},
				});
				if (res.code == 1000 && res.data.cartKey) {
					uni.setStorageSync("buyNowCartKey", res.data.cartKey);
					const _skuIdArr = encodeURIComponent(JSON.stringify(skuIdArr));
					uni.navigateTo({
						url: `/pages/order/submit?skuIdArr=${_skuIdArr}&type=C2B`,
					});
				} else {
					if (res.code == -1010) {
						that.handleShowTextToast("已超出限购数量，详情请咨询顾问");
					} else {
						that.handleShowTextToast(res.msg);
					}
				}
			} catch (error) {
				console.log("buyNowRequest", error);
			}
		},
		/**
		 * 展示弱提示
		 * @param {Object} msg 文案
		 */
		handleShowTextToast(msg) {
			try {
				this.$refs.toastPopup.showToast(msg);
			} catch (e) { }
		},
		/**
		 * 若提示按钮点击回调
		 * @param {Object} data.type 类型：confirm确定，cancel取消
		 * @param {Object} data.callBackData 呼气弹窗时传入的数据
		 */
		onToastPopupClick(data) { },
	},
};
</script>

<style lang="less" scoped>
.goodsLettering {
	font-family: FrankNew-Regular, NotoSansSC-Regular;
	padding-bottom: 64rpx;

	.goodsLettering-box {
		padding: 0 48rpx;
	}

	.goodsLettering-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		// margin-top: 64rpx;
	}

	.goodsLettering-img-box {
		// width: 750rpx;
		width: 572rpx;
		position: relative;
	}

	.container-title {
		font-family: NotoSansSC-Regular;
		font-size: 48rpx;
		font-weight: 500;
		line-height: 52rpx;
		text-align: center;
		text-transform: uppercase;
		letter-spacing: 0rpx;
		margin-bottom: 58rpx;
	}

	.container-img {
		height: 572rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		.container-img-box {
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			// position: relative;
			overflow: hidden;
		}
	}

	.img-container {
		width: 100%;
		height: 100%;
		// border: 1px solid black;

		.goodsLettering-canvas {
			width: 100%;
			height: 100%;
			transition: transform 0.5s ease;
			transform-origin: bottom; //缩放中心点
		}
	}

	.icon-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: absolute;
		right: 220rpx;
		bottom: 98rpx;

		.restore {
			font-family: NotoSansSC-Medium;
			height: 20rpx;
			font-size: 20rpx;
			line-height: 20rpx;
			text-align: center;
		}

		.icon-style {
			width: 24rpx;
			height: 24rpx;
			display: flex;
			z-index: 2;
		}
	}

	.container-content {
		padding: 40rpx 0;
		width: 100%;

		.container-describe {
			font-family: NotoSansSC-Regular;
			font-size: 20rpx;
			font-weight: normal;
			line-height: 40rpx;
			display: flex;
			align-items: center;
			letter-spacing: 0rpx;
			padding-right: 32rpx;
			color: #757575;
		}

		.container-symbol {
			font-family: NotoSansSC-Regular;
			font-weight: normal;
			font-size: 28rpx;
			line-height: 40rpx;
			color: #000000;
			margin-top: 16rpx;
			padding-left: 32rpx;
			display: flex;

			.radio-icon-box {
				display: flex;
				align-items: center;

				.selectIconStyle {
					width: 72rpx;
					height: 40rpx;
					background-size: 100% 100%;
				}

				.selectIconStyle_newYear {
					width: 24rpx;
					height: 24rpx;
					background-size: 100% 100%;
					margin-right: 8rpx;
				}
			}
		}

		.option_img_box {
			display: flex;

			.option_title {
				font-family: NotoSansSC-Regular;
				font-weight: normal;
				font-size: 28rpx;
				line-height: 40rpx;
				color: #000000;
			}

			.option_item {
				flex: 1;
				display: flex;
				flex-wrap: wrap;
			}
		}

		.container-text-area {
			display: flex;
			width: 100%;
			padding: 32rpx 0 32rpx 32rpx;
			background-color: #fafafa;

			.input-box {
				flex: 1;
				position: relative;
				display: flex;
				align-items: center;

				.item_length {
					display: flex;
					align-content: center;
				}

				.emoji-box {
					width: 510rpx;
					min-height: 48rpx;
					display: flex;
					align-items: center;
					font-size: 28rpx;
					line-height: 48rpx;
				}

				.def-content {
					font-family: NotoSansSC-Regular;
					color: #757575;
				}

				.text-num {
					font-family: FrankNew-Regular;
					font-size: 28rpx;
					line-height: 48rpx;
					color: #757575;
					width: 80rpx;
					height: 48rpx;
					text-align: right;
				}
			}

			text {
				flex-shrink: 0;
				color: #757575;
				font-size: 28rpx;
				line-height: 48rpx;
				font-family: NotoSansSC-Regular;
			}
		}

		.emoji-icon-box {
			// width: 21rpx;
			// height: 21rpx;
			display: flex;
		}
	}

	.btn {
		width: 654rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 48rpx 16rpx 48rpx 48rpx;
		font-size: 28rpx;
		font-weight: 500;
		font-family: NotoSansSC-Medium;
		margin-bottom: 0;
	}

	.submit-btn {
		color: #fff;
		background-color: #000000;
	}

	.disabel-btn-style {
		color: #757575;
		background-color: #c6c6c6;
	}

	.edit-btn {
		border: 4rpx solid #000000;
		color: #000000;
		background-color: #fff;
	}

	.attention {
		// height: 240rpx;
		width: 100%;
		position: relative;
		padding: 0 32rpx;

		.hot_region {
			width: 279rpx;
			height: 40rpx;
			position: absolute;
			right: 60px;
			bottom: 0;
		}

		.def_text {
			color: #757575;
			font-family: NotoSansSC-Regular, NotoSansSC-Regular;
		}

		text {
			font-size: 20rpx;
			line-height: 40rpx;
			display: inline-block;
		}
	}

	.check-rules {
		display: flex;
		height: 40rpx;
		width: 100%;
		margin: 16rpx 0 32rpx;
		padding-left: 32rpx;

		.check-icon {
			height: 40rpx;
			display: flex;
			align-items: center;
			margin-right: 16rpx;
			line-height: 40rpx;
			color: #757575;

			image {
				width: 20rpx;
				height: 20rpx;
			}
		}

		.check-text {
			font-size: 20rpx;
			line-height: 40rpx;
			color: #757575;
			font-family: FrankNew-Regular, NotoSansSC-Regular;
		}
	}

	.emoji {
		display: inline-block;
		vertical-align: middle;
		background-size: contain;
		background-repeat: no-repeat;
	}

	.emoji-1 {
		width: 40rpx;
		height: 40rpx;
		background-image: url(https://100000063-1252208446.file.myqcloud.com/images/刻字/icon1-black.png);
	}

	.emoji-2 {
		width: 40rpx;
		height: 40rpx;
		background-image: url(https://100000063-1252208446.file.myqcloud.com/images/刻字/icon-black.png);
	}

	.emoji-1-black {
		width: 22rpx;
		height: 23rpx;
		// margin: 0 3.5px;
		margin: 13rpx 4rpx;
		background-image: url(https://100000063-1252208446.file.myqcloud.com/images/刻字/and-icon_2.png);
		background-position: center;
	}

	.emoji-2-black {
		width: 22rpx;
		height: 22rpx;
		margin: 13rpx 4rpx;
		background-image: url(https://100000063-1252208446.file.myqcloud.com/images/刻字/xin-icon_.png);
		background-position: center;
	}

	.emoji-3-black {
		width: 22rpx;
		height: 22rpx;
		margin: 13rpx 4rpx;
		background-image: url(https://100000063-1252208446.file.myqcloud.com/images/刻字/xing-icon_.png);
		background-position: center;
	}

	.emoji-4-black {
		width: 22rpx;
		height: 22rpx;
		margin: 13rpx 4rpx;
		background-image: url(https://100000063-1252208446.file.myqcloud.com/images/刻字/gift-icon_.png);
		background-position: center;
	}

	.emoji-item,
	.emoji-preview {
		display: inline;
		font-size: 28rpx;
		// font-family: Dancing-One, Dancing-Xt;
	}

	.placeholder {
		min-width: 8rpx; //空格间距
		display: inline-block;
	}

	.btn-continner {
		display: flex;
		flex-direction: column;
		align-items: center;
		// padding-top: 20rpx;
	}

	.cursor {
		content: "";
		display: inline-block;
		width: 2rpx;
		height: 1em;
		background-color: black;
		animation: blink 1s step-end infinite;
	}

	@keyframes blink {

		from,
		to {
			opacity: 1;
		}

		50% {
			opacity: 0;
		}
	}

	.bold_text {
		color: #1a1a1a;
		font-weight: 500;
		font-family: FrankNew-Regular, NotoSansSC-Medium;
	}
}
</style>
